import re
import sys
import sqlparse
from sqlparse.tokens import DML,Keyword

class SqlparseMerge:
    merge_flag = False
    into_flag = False
    using_flag = False
    on_flag = False
    mergesql = 'INSERT INTO '
    src_table_name = ''

    def sqlparseMerge(self,sql):
        for item in sql:
            if item.value.upper() == 'MERGE' and item.ttype == DML:
                self.merge_flag = True
            if item.value.upper() == 'INTO' and item.ttype == Keyword:
                self.into_flag = True
            if item.value.upper() == 'USING' and item.ttype == Keyword:
                self.using_flag = True
                self.merge_flag = False
                self.into_flag = False
            if item.value.upper() == 'ON' and item.ttype == Keyword:
                self.on_flag = True
                self.using_flag = False

            if self.merge_flag == True and self.into_flag == True and item.is_group:
                if 'SELECT' not in item.value.upper():
                    if ' ' in item.value.upper():
                        self.mergesql += item.value.strip().upper().split(' ')[0] + ' SELECT '
                    else:
                        self.mergesql +  item.value.strip().upper() + ' SELECT '
                else:
                    if 'FROM' in item.value.upper():
                        table_name = item.value.upper().strip().split('FROM')[-1]
                        table_name = table_name.strip().split(' ')[0]
                        self.mergesql += table_name + ' SELECT '

            if self.using_flag == True and item.is_group:
                self.src_table_name += item.value.upper()

            if re.match('^VALUES.*',item.value.upper().strip()) is not None:
                self.mergesql += re.findall('\((.*?)\)',item.value.upper())[0]
                self.mergesql += ' FROM ' + self.src_table_name
                return self.mergesql

if __name__ == '__main__':
    try:
        sql = sys.argv[1]
        sql = sqlparse.format(sql.upper(),strip_comments=True).strip()
        sql = sql.replace('\n',' ').replace('\r\n',' ')
        parsed = sqlparse.parse(sql)[0]
        sqlparsemerge = SqlparseMerge()
        mergesql = sqlparsemerge.sqlparseMerge(parsed)
        print(mergesql)
    except Exception as e:
        print('error:' + str(e))
